﻿using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using Baosight.ZNH.ZMCommon;
using Baosight.Platform.Core;
using Baosight.Platform.Core.UI.Controls;
using Baosight.ZNH.ZMCommon.ChildWindows;
using Baosight.Platform.Core.ServiceModel;
using Telerik.Windows.Controls;
using Telerik.Windows.Controls.GridView;

namespace Baosight.ZNH.ZMCM.UI.ChildWindows
{
    /// <summary>  
    /// Title:OutBoundWindow
    /// Copyright:Baosight Software LTD.co Copyright (c) 2011
    /// Company:上海宝信软件股份有限公司
    /// Author: 余虎
    /// Version: 1.0
    /// History:
    ///       2011-7-5  余虎   [创建]
    ///       2011-7-26 张坤   [修改]
    ///       2011-9-21 wangkun 去掉选择库房内容
    ///<summary>  
    public partial class OutBoundWindow : EFViewCmes
    {
        private string actionType;
        public OutBoundWindow(String _dialogType)
        {
            InitializeComponent();
            base.BeforeAction += OnBeforeAction;
            Init(_dialogType);
        }
        /// <summary>
        /// 初始化父类EFViewCmesProperty的值，每次点击“确定”、“返回”时执行此方法，从新赋值
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnBeforeAction(object sender, EventArgs e)
        {
            EFViewCmesProperty _view = new EFViewCmesProperty();
            _view.DataFields = this.insertWindow.GetChildObjects<EFDataField>(null, true);
            base.ViewProperty = _view;
        }
        /// <summary>
        /// 初始化页面数据
        /// </summary>
        private void Init(string type)
        {
            type = type == null ? "insert" : type.ToLower();

            switch (type)
            {
                case "insert":
                    this.actionType = "insert";
                    this.fdNoteDate.Value = DateTime.Today.ToString("yyyy-MM-dd");//开单日期
                    base.Mode = OperationMode.Insert;
                    break;
                case "update":
                    base.Mode = OperationMode.Update;
                    break;
                default:
                    break;
            }
        }

        #region 按钮事件
        /// <summary>
        /// 下一步操作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>

        private void Next_Click(object sender, RoutedEventArgs e)
        {
            if (insertgrid.ValidateField())
            {
                base.OnQueryButtonClick(sender, e);
                ValidateCode();
            }
        }

        private void ValidateCode()
        {
            EIInfo eiInfo = new EIInfo();
            eiInfo.Set("service", "ZMCME1");
            eiInfo.Set("method", "validateDate");
            eiInfo.Set("fdNoteDate", this.fdNoteDate.Value);

            HttpServiceAgent agent = new HttpServiceAgent();
            agent.CallService(eiInfo, OnDoValidateCompleted);
        }

        /// <summary>
        /// 验证后的回调方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnDoValidateCompleted(object sender, DoWorkCompletedEventArgs e)
        {
            if (e.EIInfo.GetStatus() != -1)
            {
                if (this.ValidateField())
                {
                    if (this.insertWindow.Visibility == Visibility.Visible && this.Next.Visibility == Visibility.Visible
                        && this.Cancel1.Visibility == Visibility.Visible && this.listGrid.Visibility == Visibility.Collapsed
                        && this.grid.Visibility == Visibility.Collapsed && this.Last.Visibility == Visibility.Collapsed
                        && this.Commit.Visibility == Visibility.Collapsed && this.Cancel.Visibility == Visibility.Collapsed)
                    {
                        this.insertWindow.Visibility = Visibility.Collapsed;
                        this.Next.Visibility = Visibility.Collapsed;
                        this.Cancel1.Visibility = Visibility.Collapsed;
                        this.listGrid.Visibility = Visibility.Visible;
                        this.grid.Visibility = Visibility.Visible;
                        this.Last.Visibility = Visibility.Visible;
                        this.Commit.Visibility = Visibility.Visible;
                        this.Cancel.Visibility = Visibility.Visible;
                    }
                    if (this.fdUse2LevelBase.Value.Equals("0"))
                    {
                        this.grid.Columns[this.grid.Columns.Count - 1].IsVisible = false;
                    }
                    else
                    {
                        this.grid.Columns[this.grid.Columns.Count - 1].IsVisible = true;
                    }
                }
            }
            else
            {
                this.OnCommitMessagePopup(e.EIInfo);//操作失败，消息提醒
            }
        }
        /// <summary>
        /// 取消操作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Cancel1_Click(object sender, RoutedEventArgs e)
        {
            CmesWindows _window = this.Parent as CmesWindows;
            _window.DialogResult = false;
            _window.Close();
        }

        /// <summary>
        /// 上一步操作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>

        private void Last_Click(object sender, RoutedEventArgs e)
        {
            this.insertWindow.Visibility = Visibility.Visible;
            this.Next.Visibility = Visibility.Visible;
            this.Cancel1.Visibility = Visibility.Visible;
            this.listGrid.Visibility = Visibility.Collapsed;
            this.grid.Visibility = Visibility.Collapsed;
            this.Last.Visibility = Visibility.Collapsed;
            this.Commit.Visibility = Visibility.Collapsed;
            this.Cancel.Visibility = Visibility.Collapsed;
        }

        /// <summary>
        /// 确定提交
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Commit_Click(object sender, RoutedEventArgs e)
        {
            Button button = sender as Button;
            button.IsEnabled = false;
            TempButton = button;
            String msg = this.validateValue().ToString();
            int count = this.grid.GetCheckedEIRows().Count;

            IList<EIRow> _list = this.grid.GetCheckedEIRows() == null ? new List<EIRow>() : this.grid.GetCheckedEIRows();
            if (this.fdExportType.Value.Equals("一般出库"))
            {
                for (int i = 0; i < _list.Count; i++)
                {
                    if (this.grid.GetCheckedEIRows()[i]["fdMaterialType"] != null)
                    {
                        if (this.grid.GetCheckedEIRows()[i]["fdMaterialType"].ToString() == "")
                        {
                            msg = "请选择物资类型！";
                            break;
                        }
                    }
                    else
                    {
                        msg = "请选择物资类型！";
                        break;
                    }
                }
            }

            if (msg == "1")
            {
                base.Submit(OperationMode.Insert, "ZMCME1", "insert", DataRange.CheckedItems, DoCommitCompleted, null);
            }else
            {
                this.OpenEFWindowAlert(msg, true);
                return;
            }

        }

        /// <summary>
        /// 取消操作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Cancel_Click(object sender, RoutedEventArgs e)
        {
            CmesWindows _window = this.Parent as CmesWindows;
            _window.DialogResult = false;
            _window.Close();
        }

        #endregion
        /// <summary>
        /// 领料申请单customview
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void INQU_fdResourceNoteCode_ValueChanged(object sender, ValueChangedEventArgs e)
        {
            if (e.NewValue == null && e.OldValue.Equals(""))
            {
                return;
            }
            EFDataField field = sender as EFDataField;
            EFCustomDataPicker picker = field.Content as EFCustomDataPicker;
            if (picker.ItemObject != null)
            {
                if (!picker.ItemObject.Equals(""))
                {
                    this.INQU_fdApplicationId.Value = picker.ItemObject.GetType().GetProperty("fdKeyId").GetValue(picker.ItemObject, null);
                    this.fdResourceNoteCode.Value = picker.ItemObject.GetType().GetProperty("fdApplicationCode").GetValue(picker.ItemObject, null);
                    this.fdMonth.Value = picker.ItemObject.GetType().GetProperty("fdMonth").GetValue(picker.ItemObject, null);
                    this.fdYear.Value = picker.ItemObject.GetType().GetProperty("fdYear").GetValue(picker.ItemObject, null);
                    this.fdApplicationDepartment.Value = picker.ItemObject.GetType().GetProperty("fdApplicationDepartment").GetValue(picker.ItemObject, null);
                    this.fdApplicationDepartmentName.Value = picker.ItemObject.GetType().GetProperty("fdApplicationDepartmentName").GetValue(picker.ItemObject, null);
                }
                else
                {
                    this.INQU_fdApplicationId.Value = "";
                    this.fdResourceNoteCode.Value = "";
                    this.fdMonth.Value = "";
                    this.fdYear.Value = "";
                    this.fdApplicationDepartment.Value = "";
                    this.fdApplicationDepartmentName.Value = "";
                }
            }
        }

        private void INQU_fdEditor_ValueChanged(object sender, ValueChangedEventArgs e)
        { 
        }

        /// <summary>
        /// 计算实发数量
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void grid_CellEditEnded(object sender, Telerik.Windows.Controls.GridViewCellEditEndedEventArgs e)
        {
            IEFColumn column = e.Cell.Column as IEFColumn;
            UIBaseEntity obj = e.Cell.ParentRow.DataContext as UIBaseEntity;
            EIRow row = obj.GetEIRow();
            if (column != null)
            {
                if (column.eColumnName.Equals("fdActualNumber"))
                {
                    
                    var fdPrice = row["fdPrice"];
                    row["fdSum"] = Convert.ToDouble(fdPrice) * Convert.ToDouble(e.NewData);
                }
                //if (!this.fdUse2LevelBase.Value.ToString().Equals("1") || this.fdUse2LevelBase.Value.ToString() != "1")
                //{
                //    this.grid.Columns[this.grid.Columns.Count - 1].IsVisible = false;
                //}
                //else
                //{
                //        if (column.eColumnName.Equals("fdDepotName"))
                //        {
                //            EFCustomDataPicker picker = (e.Cell.Content as GridViewEditorPresenter).Content as EFCustomDataPicker;
                //            if (picker.ItemObject != null)
                //            {
                //                if (picker.ItemObject.ToString() != "" || !"".Equals(picker.ItemObject.ToString().Trim()))
                //                {
                //                    row["fdDepotCode"] = picker.ItemObject.GetType().GetProperty("fdDepotCode").GetValue(picker.ItemObject, null);
                //                }
                //                else
                //                {
                //                    row["fdDepotCode"] = "";
                //                    row["fdDepotName"] = "";
                //                }
                //            }
                //            if (row["fdDepotName"] == null || row["fdDepotName"].ToString().Trim() == "")
                //            {
                //                this.OpenEFWindowAlert("请选择库房名称！", true);
                //            }
                //        }
                //}
              }
           
        }

        /// <summary>
        /// 重写了确定按钮执行事件的回调方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public override void DoCommitCompleted(object sender, DoWorkCompletedEventArgs e)
        {
            EIInfo inInfo = e.EIInfo;
            if (inInfo.Status == -1)
            {
                this.TempButtonOpen(true);
                this.OnCommitMessagePopup(inInfo);//操作失败，消息提醒
            }
            else
            {
                if ("insert".Equals(actionType))
                {
                    NotifyViewDataChanged(e.EIInfo.Get("fdNoteCode").ToString());
                }
                EFWindow window = this.Parent as EFWindow;
                window.DialogResult = true;
                window.Close();
            }
        }

        /// <summary>
        /// 用于校验数据
        /// </summary>
        private String validateValue()
        {
            IList<EIRow> _list = this.grid.GetCheckedEIRows() == null ? new List<EIRow>() : this.grid.GetCheckedEIRows();

            if (_list.Count <= 0)
            {
                return "请选择一条或多条记录进行操作!";
            }
            else
            {
                for (int i = 0; i < _list.Count; i++)
                {
                    EIRow row = (EIRow)_list[i];
                    Double fdActualNumber = Convert.ToDouble(((row["fdActualNumber"] == null) ? 0 : row["fdActualNumber"]).ToString());
                    Double fdAuditNumber = Convert.ToDouble(((row["fdAuditNumber"] == null) ? 0 : row["fdAuditNumber"]).ToString());//审批数量
                    Double fdExportedNumber = Convert.ToDouble(((row["fdExportedNumber"] == null) ? 0 : row["fdExportedNumber"]).ToString());//已发数量
                    Double fdNum = Convert.ToDouble(((row["fdNum"] == null) ? 0 : row["fdNum"]).ToString());//库存数量

                    if (fdNum == 0)
                    {
                        return row["fdMaterialName"].ToString() + "的库存数量为0，无法办理出库！";
                    }

                    if (fdActualNumber > fdAuditNumber - fdExportedNumber)
                    {
                        return "实发数量不能大于审批数量减去已发数量！";
                    }
                    if (fdActualNumber < 0)
                    {
                        return "实发数量不能为负数！";
                    }

                    if (row["fdBusinessType"] == null || "".Equals(row["fdBusinessType"].ToString().Trim()))
                        return "请选择业务类型!";

                    if (row["fdMaterialType"] == null || "".Equals(row["fdMaterialType"].ToString().Trim()))
                        return "请选择物资类型!";

                    //if (this.fdUse2LevelBase.Value.Equals("1"))
                    //{
                    //    if (this.EIDataContext.GetBlock("result").GetRow(i)["fdBusinessType"] != null)
                    //    {
                    //        if (this.EIDataContext.GetBlock("result").GetRow(i)["fdBusinessType"].ToString().Trim() == "")
                    //            return "请选择业务类型!";
                    //    }
                    //    else return "请选择业务类型!";
                    //    if (this.EIDataContext.GetBlock("result").GetRow(i)["fdDepotName"] != null)
                    //    {
                    //        if (this.EIDataContext.GetBlock("result").GetRow(i)["fdDepotName"].ToString().Trim() == "")
                    //            return "请选择二级库房!";
                    //    }
                    //    else return "请选择二级库房!";
                    //}
                }
            }
            return "1";
        }
    }
}
